<?php

namespace App\Libraries;

use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
/**
 * 联通云oss
 */
class CUOss
{
    private $s3;

    private $bucket;

    public function __construct($Bucket = '')
    {
        $config = [
            'access_key' => '7B79C8FD47514EA6BD93147BC02335549109',
            'secret_key' => 'A4E1E45B76D4434FB25A9C886CEA59913669',
            'region' => 'cn-shanghai-1',
            'endpoint' => 'http://obs-sh.cucloud.cn',
        ];
        $this->bucket = $Bucket;
        $this->s3 = new S3Client([
            'version' => 'latest',
            'region' => $config['region'],
            'endpoint' => $config['endpoint'],
            'credentials' => [
                'key' => $config['access_key'],
                'secret' => $config['secret_key']
            ],
        ]);
    }


    // 上传到联通云
    public function upload($key, $file)
    {
        if (empty($key)) return false;
        if (empty($file)) return false;

        try {
            $params = [
                'Bucket' => $this->bucket,
                'Key' => $key
            ];
            if (is_file($file)) {
                $params['SourceFile'] = $file;
            } else {
                $params['Body'] = $file;
            }
            $res = $this->s3->putObject($params);
            if (!empty($res['ObjectURL'])) {
                return $key;
            } else {
                return false;
            }
        } catch (S3Exception $e) {
            return false;
        }
    }

    // 获取访问链接授权
    public function urlAuth($url, $expire_time = 60)
    {
        $fullPath = parse_url($url)['path'];
        $key = ltrim($fullPath, '/');
        $command = $this->s3->getCommand('GetObject', [
            'Bucket' => $this->bucket,
            'Key' => $key,
        ]);

        // 获取预签名的URL
        $request = $this->s3->createPresignedRequest($command, "+$expire_time minutes");
        $Uri = (string)$request->getUri();
        return $Uri;
    }

}
